package cn.ljw_jhc.booksearch;

import android.net.Uri;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by info on 16/12/22.
 */
public class DoubanFetcher {

    private static final String TAG = "DoubanFetcher";

    private static final String API_KEY="yourApiKeyHere";
    private List<String> list;
    public void show(){
        list.add(0,"search");
    }


    public byte[] getURL(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer))>0){
                outputStream.write(buffer,0,bytesRead);
            }
            outputStream.close();
            return outputStream.toByteArray();
        } finally {
            connection.disconnect();
        }

    }

    public String getURLString(String url) throws IOException {
        return new String(getURL(url));
    }

    public List<BookItem> fetchItem(String KEY){
        List<BookItem> items = new ArrayList<>();
        try {
            String url = Uri.parse("https://api.douban.com/v2/book/")
                    .buildUpon()
                    .appendPath("search")
                    .appendQueryParameter("q",KEY)//!!!!!
                    .build().toString();
            String jsonString = getURLString(url);
            Log.i(TAG, "Received JSON: " + jsonString);
            JSONObject obj = new JSONObject(jsonString);
            parseItems(items,obj);
        } catch (IOException e) {
            Log.e(TAG, "Failed to fetch items", e);
        } catch (JSONException je) {
            Log.e(TAG, "Failed to parse JSON", je);
        }
        return items;
    }

    private void parseItems(List<BookItem> items,JSONObject jsonBody) throws JSONException {
        JSONArray books = jsonBody.getJSONArray("books");
        for (int i = 0 ; i<books.length();i++){
            BookItem item = new BookItem();
            JSONObject sub =books.getJSONObject(i);
            String title = sub.getString("title");
            String url =  sub.getString("alt");
            String imgURL = sub.getJSONObject("images").getString("medium");
            item.setTitle(title);
            item.setImgURL(imgURL);
            item.setUrl(url);

            items.add(item);
        }


    }
}
